<template>
  <div class="a4-container">
    <div class="header">
      <div class="header-left">
        <h1><el-icon><Document /></el-icon>文件及QA对审核</h1>
      </div>
      <div class="user-info">
        <span class="welcome">欢迎您 <span class="real-name">{{ realName }}</span></span>
        <div class="user-profile" @click="handleChangePassword">
          <el-icon class="user-icon"><User /></el-icon>
          
          <span class="username">{{ username }}</span>
        </div>
        <button class="logout-btn" @click="handleLogout">
          <el-icon><SwitchButton /></el-icon> 退出登录
        </button>
      </div>
    </div>
    
    <div class="stats-cards">
      <div class="processed-count-text">
        <el-icon><DataLine /></el-icon> 已处理文件数：{{ stats.processed }}
        <el-divider direction="vertical" />
        <el-icon><Timer /></el-icon> 待处理文件数：{{ stats.pending }}
        <el-divider direction="vertical" />
        <el-icon><DataLine /></el-icon> 已处理QA数：{{ stats.qaProcessed }}
        <el-divider direction="vertical" />
        <el-icon><Timer /></el-icon> 待处理QA数：{{ stats.qaPending }}
      </div>
    </div>
    
    <!-- 视图切换按钮 -->
    <div class="view-switch">
      <el-radio-group v-model="currentView" @change="handleViewChange" size="large">
        <el-radio-button label="file">文件审核</el-radio-button>
        <el-radio-button label="last">QA对审核</el-radio-button>
      </el-radio-group>
    </div>
    
    <!-- 文件审核视图 -->
    <div class="history-list-section" v-if="currentView === 'file'">
      <el-card class="history-list-card">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <h2>文件列表</h2>
              <div class="header-actions">
                <el-radio-group v-model="fileViewType" @change="handleFileViewTypeChange" size="small">
                  <el-radio-button label="pending">未处理</el-radio-button>
                  <el-radio-button label="processed">已处理</el-radio-button>
                </el-radio-group>
                <el-button type="primary" @click="refreshFileList">
                  <el-icon><Refresh /></el-icon>
                  刷新列表
                </el-button>
              </div>
            </div>
          </div>
        </template>
        
        <div class="file-list">
          <div v-for="item in paginatedFileList" 
               :key="item.id" 
               class="file-item"
               :class="{ 'file-item-active': previewItem && previewItem.id === item.id }"
               @click="previewDetail(item)">
            <div class="file-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="file-info">
              <div class="file-name" :title="item.articleTitle || item.fileName || '未命名文件'">
                {{ item.articleTitle || item.fileName || '未命名文件' }}
              </div>
              <div class="file-time">上传时间：{{ formatDate(item.createTime || item.uploadTime) }}</div>
            </div>
            <div class="file-actions">
              <el-tooltip content="下载文件" placement="top">
                <el-button 
                  type="primary" 
                  circle 
                  @click.stop="downloadPdf(item)"
                  :loading="item.downloading"
                  size="small">
                  <el-icon><Download /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
            <el-tag :type="getFileStatusType(item.status)" class="file-status">
              {{ getFileStatusText(item.status) }}
            </el-tag>
          </div>
        </div>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="50"
            :total="filteredFileList.length"
            layout="total, prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 右侧详情预览 -->
      <div class="detail-preview" v-if="previewItem">
        <el-card>
          <template #header>
            <div class="preview-header">
              <h3>文件详情</h3>
              <el-tag :type="getFileStatusType(previewItem.status)">
                {{ getFileStatusText(previewItem.status) }}
              </el-tag>
            </div>
          </template>
          <div class="preview-content">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="文件ID">
                {{ previewItem.id || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="文件名">
                {{ previewItem.articleTitle || previewItem.fileName || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="专业">
                {{ previewItem.major || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="作者信息">
                <div class="content-wrapper">
                  <div :class="['content-block', { expanded: expandedBlocks.authorInfo }]">{{ previewItem.authorInfo || '-' }}</div>
                  <span v-if="previewItem.authorInfo && previewItem.authorInfo.length > 100" 
                        class="expand-btn" 
                        @click="toggleBlock('authorInfo')">
                    {{ expandedBlocks.authorInfo ? '收起' : '展开' }}
                  </span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="内容摘要">
                <div class="content-wrapper">
                  <div :class="['content-block', { expanded: expandedBlocks.contentSummary }]">{{ previewItem.contentSummary || '-' }}</div>
                  <span v-if="previewItem.contentSummary && previewItem.contentSummary.length > 100" 
                        class="expand-btn" 
                        @click="toggleBlock('contentSummary')">
                    {{ expandedBlocks.contentSummary ? '收起' : '展开' }}
                  </span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="研究结论">
                <div class="content-wrapper">
                  <div :class="['content-block', { expanded: expandedBlocks.researchConclusion }]">{{ previewItem.researchConclusion || '-' }}</div>
                  <span v-if="previewItem.researchConclusion && previewItem.researchConclusion.length > 100" 
                        class="expand-btn" 
                        @click="toggleBlock('researchConclusion')">
                    {{ expandedBlocks.researchConclusion ? '收起' : '展开' }}
                  </span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="Markdown内容">
                <div class="content-wrapper">
                  <div :class="['content-block', { expanded: expandedBlocks.markdown }]">{{ previewItem.markdown || '-' }}</div>
                  <span v-if="previewItem.markdown && previewItem.markdown.length > 100" 
                        class="expand-btn" 
                        @click="toggleBlock('markdown')">
                    {{ expandedBlocks.markdown ? '收起' : '展开' }}
                  </span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="审核意见">
                <div class="content-block">{{ previewItem.reviewComment || '-' }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="上传时间">
                {{ previewItem.createTime ? new Date(previewItem.createTime).toLocaleString() : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="更新时间">
                {{ previewItem.updateTime ? new Date(previewItem.updateTime).toLocaleString() : '-' }}
              </el-descriptions-item>
            </el-descriptions>
            
            <div class="preview-actions" v-if="fileViewType !== 'processed'">
              <el-button 
                type="success" 
                @click="approveFile(previewItem)"
                :disabled="previewItem.status === 1">
                通过
              </el-button>
              <el-button 
                type="danger" 
                @click="rejectFile(previewItem)"
                :disabled="previewItem.status === 2">
                驳回
              </el-button>
              <el-button 
                type="primary" 
                @click="submitFileStatus(previewItem)"
                :disabled="!previewItem.status || previewItem.status === 0"
                :loading="loading">
                提交
              </el-button>
            </div>
            <div class="preview-actions" v-else>
              <!-- 已处理视图不需要任何按钮 -->
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- QA对审核视图 -->
    <div class="history-list-section" v-if="currentView === 'last'">
      <el-card class="history-list-card">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <h2>QA对列表</h2>
              <div class="header-actions">
                <el-radio-group v-model="qaViewType" @change="handleQaViewTypeChange" size="small">
                  <el-radio-button label="pending">未处理</el-radio-button>
                  <el-radio-button label="processed">已处理</el-radio-button>
                </el-radio-group>
                <el-button type="primary" @click="refreshFileList">
                  <el-icon><Refresh /></el-icon>
                  刷新列表
                </el-button>
              </div>
            </div>
          </div>
        </template>
        
        <div class="file-list">
          <div v-for="item in paginatedPdfList" 
               :key="item.id" 
               class="file-item"
               :class="{ 'file-item-active': currentPdf && currentPdf.id === item.id }"
               @click="selectPdf(item)">
            <div class="file-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="file-info">
              <div class="file-name" :title="item.fileName || item.articleTitle || '未命名文件'">
                {{ item.fileName || item.articleTitle || '未命名文件' }}
              </div>
              <div class="file-time">上传时间：{{ formatDate(item.createTime || item.uploadTime) }}</div>
            </div>
            <div class="file-actions">
              <el-tooltip content="下载文件" placement="top">
                <el-button 
                  type="primary" 
                  circle 
                  @click.stop="downloadPdf(item)"
                  :loading="item.downloading"
                  size="small">
                  <el-icon><Download /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
            <el-tag :type="getFileStatusType(item.status)" class="file-status">
              {{ getFileStatusText(item.status) }}
            </el-tag>
          </div>
        </div>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pdfCurrentPage"
            :page-size="50"
            :total="pdfList.length"
            layout="total, prev, pager, next"
            @current-change="handlePdfCurrentChange"
          />
        </div>
      </el-card>

      <!-- QA对审核详情 -->
      <div class="detail-preview" v-if="currentPdf">
        <el-card>
          <template #header>
            <div class="preview-header">
              <h3>QA对审核</h3>
            </div>
          </template>
          <div class="preview-content">
            <div v-if="qaList.length > 0">
              <div v-for="(qa, index) in qaList" 
                   :key="qa.id"
                   :class="['qa-item', { 
                     'qa-item-approved': qa.status === 'approved', 
                     'qa-item-rejected': qa.status === 'rejected',
                     'qa-item-current': index === currentPage - 1
                   }]">
                <div class="qa-header">
                  <span class="qa-index">问答对 #{{ index + 1 }}</span>
                  <div class="qa-status" v-if="qa.status">
                    <el-tag :type="getQaStatusType(qa.statusCode)">
                      {{ getQaStatusText(qa.statusCode) }}
                    </el-tag>
                  </div>
                </div>
                <div class="qa-content">
                  <div class="qa-field">
                    <label>问题：</label>
                    <div class="qa-text" v-if="!qa.editing">{{ qa.instruction }}</div>
                    <el-input
                      v-else
                      v-model="qa.instruction"
                      type="textarea"
                      rows="3"
                      placeholder="请输入问题"
                    />
                  </div>
                  <div class="qa-field">
                    <label>答案：</label>
                    <div class="qa-text" v-if="!qa.editing">{{ qa.output }}</div>
                    <el-input
                      v-else
                      v-model="qa.output"
                      type="textarea"
                      rows="5"
                      placeholder="请输入答案"
                    />
                  </div>
                  <div class="qa-field">
                    <label>AI回答：</label>
                    <div class="qa-text ai-output">{{ qa.llmOutput }}</div>
                  </div>
                  <div class="qa-field answer-select" v-if="qaViewType === 'pending'">
                    <label>选择通过答案：</label>
                    <el-radio-group v-model="qa.selectedAnswer" class="answer-radio-group">
                      <el-radio label="normal">人工答案</el-radio>
                      <el-radio label="ai">AI答案</el-radio>
                    </el-radio-group>
                  </div>
                  <div class="qa-actions">
                    <div class="qa-edit-actions" v-if="qa.editing">
                      <el-button type="primary" @click="confirmEdit(index)">确认</el-button>
                      <el-button @click="cancelEdit(index)">取消</el-button>
                    </div>
                    <div class="qa-review-actions" v-else>
                      <template v-if="qaViewType === 'pending'">
                        <el-button 
                          type="primary" 
                          @click.stop="editQa(index)">
                          <el-icon><Edit /></el-icon>
                          编辑
                        </el-button>
                        <el-button 
                          :type="qa.status === 'approved' ? 'info' : 'success'"
                          @click.stop="qa.status === 'approved' ? cancelApprove(index) : approveQa(index)"
                          :disabled="qa.status === 'rejected'">
                          <el-icon><Check /></el-icon>
                          {{ qa.status === 'approved' ? '取消通过' : '通过' }}
                        </el-button>
                        <el-button 
                          :type="qa.status === 'rejected' ? 'info' : 'danger'"
                          @click.stop="qa.status === 'rejected' ? cancelReject(index) : rejectQa(index)"
                          :disabled="qa.status === 'approved'">
                          <el-icon><Close /></el-icon>
                          {{ qa.status === 'rejected' ? '取消驳回' : '驳回' }}
                        </el-button>
                      </template>
                      <template v-else>
                        <el-button 
                          type="primary" 
                          @click.stop="downloadQaJson()">
                          <el-icon><Download /></el-icon>
                          下载QA对
                        </el-button>
                      </template>
                    </div>
                  </div>
                  <div class="qa-feedback" v-if="qa.feedback">
                    <label>驳回原因：</label>
                    <div class="feedback-text">{{ qa.feedback }}</div>
                  </div>
                </div>
              </div>
              
              <!-- 提交按钮 -->
              <div class="submit-section">
                <el-button 
                  type="success" 
                  size="large"
                  @click="saveAllChanges"
                  :disabled="!hasChanges">
                  <el-icon><Check /></el-icon>
                  提交所有更改
                </el-button>
              </div>
            </div>
            <div v-else class="no-data">
              当前文件暂无QA对
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';
import { Download, Refresh, Clock, Check, View, Edit, Close, DataLine, Timer, Document, SwitchButton, User } from '@element-plus/icons-vue';
import axios from 'axios';
import { h } from 'vue';
import { ip } from '@/config/baseURL';

// 创建TextEllipsis组件
const TextEllipsis = {
  props: {
    content: {
      type: String,
      default: ''
    },
    maxLines: {
      type: Number,
      default: 4
    },
    id: {
      type: [String, Number],
      default: () => Math.random().toString(36).substr(2, 9)
    }
  },
  data() {
    return {
      expanded: false,
      needsExpansion: false,
      maxHeight: 0,
      contentHeight: 0
    };
  },
  mounted() {
    this.checkContentHeight();
    window.addEventListener('resize', this.checkContentHeight);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.checkContentHeight);
  },
  watch: {
    content() {
      this.$nextTick(() => {
        this.checkContentHeight();
      });
    }
  },
  methods: {
    checkContentHeight() {
      this.$nextTick(() => {
        const contentElement = this.$refs.content;
        if (contentElement) {
          const lineHeight = 24;
          this.maxHeight = lineHeight * this.maxLines;
          this.contentHeight = contentElement.scrollHeight;
          this.needsExpansion = this.contentHeight > this.maxHeight;
        }
      });
    },
    toggleExpand() {
      this.expanded = !this.expanded;
    }
  },
  render() {
    return h('div', { class: 'text-ellipsis-container' }, [
      h('div', {
        ref: 'content',
        class: ['content-block', { 'text-collapsed': !this.expanded && this.needsExpansion }],
        style: !this.expanded && this.needsExpansion 
          ? { maxHeight: `${this.maxHeight}px`, overflow: 'hidden' } 
          : { maxHeight: 'none' }
      }, this.content),
      this.needsExpansion ? h('a', {
        class: 'toggle-expand',
        onClick: () => this.toggleExpand()
      }, this.expanded ? '收起' : '展开') : null
    ]);
  }
};

export default {
  name: 'A4Main',
  components: {
    Download,
    Refresh,
    Clock,
    Check,
    View,
    Edit,
    Close,
    TextEllipsis,
    DataLine,
    Timer,
    Document,
    SwitchButton,
    User
  },
  setup() {
    const router = useRouter();
    const username = ref('');
    const realName = ref(''); // 添加realName
    const pdfList = ref([]);
    const fileViewList = ref([]);
    const currentView = ref('file');
    const currentPdf = ref(null);
    const qaList = ref([]);
    const originalQaList = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const qaStatusList = ref([]);
    const fileStatusList = ref([]);
    const stats = ref({
      pending: 0,
      processed: 0,
      qaPending: 0,
      qaProcessed: 0
    });
    const pageSize = ref(50);
    const previewItem = ref(null);
    const pdfCurrentPage = ref(1);
    const pdfPageSize = ref(50);
    const qaViewType = ref('pending');
    const fileViewType = ref('pending');
    const expandedBlocks = reactive({
      authorInfo: false,
      contentSummary: false,
      researchConclusion: false,
      markdown: false
    });

    const toggleBlock = (blockName) => {
      expandedBlocks[blockName] = !expandedBlocks[blockName];
    };

    // 计算是否有更改
    const hasChanges = computed(() => {
      if (currentView.value === 'last') {
        return qaStatusList.value.length > 0;
      } else {
        return fileStatusList.value.length > 0;
      }
    });

    // 计算当前显示的QA对
    const currentQa = computed(() => {
      return qaList.value[currentPage.value - 1] || {};
    });

    // 初始化数据
    const initializeData = async () => {
      try {
        loading.value = true;
        username.value = localStorage.getItem('username') || '用户';
        
        if (currentView.value === 'file') {
          await fetchFileViewList();
        } else {
          await fetchPdfList();
          await fetchStats();
        }
      } catch (error) {
        console.error('初始化数据失败:', error);
        ElMessage.error('初始化数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取PDF列表
    const fetchPdfList = async () => {
      try {
        loading.value = true;
        // const response = await request.get('http://10.137.10.169:8080/api/me/reviewTask/file');
        const response = await request.get(ip + `/api/me/reviewTask/file`);
        console.log("返回的数据", response.data);
        
        if (response.data.code === 200) {
          // 获取每个文件的详细信息
          const fileDetails = await Promise.all(
            response.data['last-view'].map(async (item) => {
              try {
                // const detailResponse = await request.get(`http://10.137.10.169:8080/api/file/info/${item.fileId}`);
                const detailResponse = await request.get(ip + `/api/file/info/${item.fileId}`);
                console.log("第579行");
                if (detailResponse.data.code === 200) {
                  return {
                    ...item,
                    downloading: false,
                    fileName: detailResponse.data.data.fileName
                  };
                }
                return {
                  ...item,
                  downloading: false,
                  fileName: `文件${item.fileId}`
                };
              } catch (error) {
                console.error(`获取文件${item.fileId}详情失败:`, error);
                return {
                  ...item,
                  downloading: false,
                  fileName: `文件${item.fileId}`
                };
              }
            })
          );
          
          pdfList.value = fileDetails;
          // 如果有文件，自动选择第一个文件
          if (fileDetails.length > 0) {
            await selectPdf(fileDetails[0]);
          }
        } else {
          throw new Error(response.data.msg || '获取PDF列表失败');
        }
      } catch (error) {
        console.error('获取PDF列表失败:', error);
        ElMessage.error('获取PDF列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取QA列表
    const fetchQaList = async (pdfId) => {
      try {
        loading.value = true;
        
        // const response = await request.get(`http://10.137.10.169:8080/api/me/reviewTask/qa/${pdfId}`);
        const response = await request.get(ip + `/api/me/reviewTask/qa/${pdfId}`);
        console.log("请求的文件id：", pdfId);
        console.log("问答对数据：", response.data);
        
        if (response.data.code === 200) {
          const qaData = response.data['qa-last'] || [];
          
          qaList.value = qaData.map(qa => {
            console.log('处理QA对:', qa);
            return {
              ...qa,
              editing: false,
              status: getStatusText(qa.status),
              statusCode: qa.status,
              feedback: qa.feedback || '',
              instruction: qa.instruction || '',
              output: qa.output || '',
              llmOutput: qa.llmOutput || '',
              selectedAnswer: 'normal'
            };
          });
          
          console.log('处理后的QA列表:', qaList.value);
          originalQaList.value = JSON.parse(JSON.stringify(qaList.value));
          qaStatusList.value = [];
          currentPage.value = 1;
        } else {
          qaList.value = [];
          originalQaList.value = [];
          qaStatusList.value = [];
          throw new Error(response.data.msg || '获取问答对数据失败');
        }
      } catch (error) {
        console.error('获取问答对列表失败:', error);
        ElMessage.error('获取问答对列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 1:
          return '等待审核';
        case 2:
          return '计算机老师审核通过';
        case 3:
          return '计算机老师审核不通过';
        case 4:
          return '最后审核通过';
        case 5:
          return '最后审核不通过';
        case 6:
          return '被标记';
        default:
          return '未知状态';
      }
    };

    // 获取状态类型（用于标签颜色）
    const getStatusType = (status) => {
      switch (status) {
        case 1:
          return 'info';
        case 2:
          return 'success';
        case 3:
          return 'danger';
        case 4:
          return 'success';
        case 5:
          return 'danger';
        case 6:
          return 'warning';
        default:
          return 'info';
      }
    };

    // 选择PDF
    const selectPdf = async (pdf) => {
      try {
        if (hasChanges.value) {
          const confirm = window.confirm('有未保存的更改，是否继续？');
          if (!confirm) return;
        }
        currentPdf.value = pdf;
        currentPage.value = 1;
        
        // 获取QA对列表
        // const response = await request.get(`http://10.137.10.169:8080/api/Static/qa/${pdf.id}`);
        const response = await request.get(ip + `/api/Static/qa/${pdf.id}`);
        console.log("QA对数据：", response.data);
        
        if (response.data.code === 200) {
          const qaData = response.data.data || [];
          
          qaList.value = qaData.map(qa => {
            return {
              ...qa,
              editing: false,
              status: getStatusText(qa.status),
              statusCode: qa.status,
              feedback: qa.feedback || '',
              instruction: qa.instruction || '',
              output: qa.output || '',
              llmOutput: qa.llmOutput || '',
              selectedAnswer: 'normal'
            };
          });
          
          console.log('处理后的QA列表:', qaList.value);
          originalQaList.value = JSON.parse(JSON.stringify(qaList.value));
          qaStatusList.value = [];
          currentPage.value = 1;
        } else {
          qaList.value = [];
          originalQaList.value = [];
          qaStatusList.value = [];
          throw new Error(response.data.msg || '获取问答对数据失败');
        }
      } catch (error) {
        console.error('选择PDF失败:', error);
        ElMessage.error('选择PDF失败');
      }
    };

    // 编辑QA对
    const editQa = (index) => {
      try {
        console.log('点击编辑按钮，index:', index);
        console.log('当前qaList:', qaList.value);
        
        const qa = qaList.value[index];
        if (!qa) {
          console.error('未找到对应的QA对');
          return;
        }
        
        console.log('当前QA对:', qa);
        
        // 设置编辑状态
        qaList.value = qaList.value.map((item, i) => {
          if (i === index) {
            return {
              ...item,
              editing: true
            };
          }
          return item;
        });
        
        console.log('更新后的qaList:', qaList.value);
      } catch (error) {
        console.error('编辑失败:', error);
        ElMessage.error('编辑失败');
      }
    };

    // 确认编辑
    const confirmEdit = async (index) => {
      try {
        const qa = qaList.value[index];
        if (!qa) {
          console.error('未找到对应的QA对');
          return;
        }
        
        const requestData = {
          output: qa.output,
          input: "",
          system: "",
          instruction: qa.instruction,
          creatorId: 0,
          id: qa.id,
          fileId: currentPdf.value.id,
          status: qa.statusCode || 0
        };

        console.log("更新QA对的数据：", requestData);
        // const response = await request.post('http://10.137.10.169:8080/api/update/qa', requestData);
        const response = await request.post(ip + `/api/update/qa`, requestData);
        
        if (response.data.code === 200) {
          ElMessage.success('更新成功');
          qaList.value[index] = {
            ...qa,
            editing: false
          };
          // 更新原始数据
          originalQaList.value[index] = { ...qaList.value[index] };
        } else {
          throw new Error(response.data.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新失败:', error);
        ElMessage.error('更新失败');
      }
    };

    // 取消编辑
    const cancelEdit = (index) => {
      try {
        const originalQa = originalQaList.value[index];
        if (!originalQa) {
          console.error('未找到原始QA对数据');
          return;
        }
        
        qaList.value[index] = {
          ...originalQa,
          editing: false
        };
        
        console.log('取消编辑，恢复原始数据:', qaList.value[index]);
      } catch (error) {
        console.error('取消编辑失败:', error);
        ElMessage.error('取消编辑失败');
      }
    };

    // 保存所有更改
    const saveAllChanges = async () => {
      try {
        loading.value = true;
        // const response = await request.post('http://10.137.10.169:8080/api/view/qa/last', qaStatusList.value);
        const response = await request.post(ip + `/api/view/qa/last`, qaStatusList.value);
        
        if (response.data.code === 200) {
          ElMessage.success('提交成功');
          qaStatusList.value = [];
          // 重新获取QA列表和PDF列表
          await Promise.all([
            fetchQaList(currentPdf.value.id),
            fetchPdfList()
          ]);
          // 重新获取QA对列表
          if (currentPdf.value) {
            await fetchQaList(currentPdf.value.id);
          }
        } else {
          throw new Error(response.data.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      } finally {
        loading.value = false;
      }
    };

    // 通过问答对
    const approveQa = async (index) => {
      const qa = qaList.value[index];
      if (!qa.selectedAnswer) {
        ElMessage.warning('请先选择要通过的答案类型');
        return;
      }
      if (qa.selectedAnswer === 'ai') {
        qa.status = 'approved';
        qa.feedback = '';
        // status为3
        updateQaStatusList(qa.id, 3, 'ai');
      } else {
        qa.status = 'approved';
        qa.feedback = '';
        // status为1
        updateQaStatusList(qa.id, 1, 'normal');
      }
      ElMessage.success('审核通过成功');
    };

    function updateQaStatusList(id, status, selectedAnswer) {
      const existingIndex = qaStatusList.value.findIndex(item => item.id === id);
      if (existingIndex !== -1) {
        qaStatusList.value[existingIndex] = { id, status, selectedAnswer };
      } else {
        qaStatusList.value.push({ id, status, selectedAnswer });
      }
    }

    // 驳回问答对
    const rejectQa = async (index) => {
      try {
        const qa = qaList.value[index];
        qa.status = 'rejected';
        qa.feedback = '';
        
        const existingIndex = qaStatusList.value.findIndex(item => item.id === qa.id);
        if (existingIndex !== -1) {
          qaStatusList.value[existingIndex].status = 2;
        } else {
          qaStatusList.value.push({
            id: qa.id,
            status: 2
          });
        }
        
        ElMessage.success('驳回成功');
      } catch (error) {
        console.error('驳回失败:', error);
        ElMessage.error('驳回失败');
      }
    };

    // 取消通过
    const cancelApprove = async (index) => {
      try {
        const qa = qaList.value[index];
        qa.status = null;
        qa.feedback = '';
        
        qaStatusList.value = qaStatusList.value.filter(item => item.id !== qa.id);
        
        ElMessage.success('已取消通过');
      } catch (error) {
        console.error('取消通过失败:', error);
        ElMessage.error('取消通过失败');
      }
    };

    // 取消驳回
    const cancelReject = async (index) => {
      try {
        const qa = qaList.value[index];
        qa.status = null;
        qa.feedback = '';
        
        qaStatusList.value = qaStatusList.value.filter(item => item.id !== qa.id);
        
        ElMessage.success('已取消驳回');
      } catch (error) {
        console.error('取消驳回失败:', error);
        ElMessage.error('取消驳回失败');
      }
    };

    // 退出登录
    const handleLogout = () => {
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('username');
      localStorage.removeItem('userRole');
      localStorage.removeItem('token');
      router.push('/login');
    };

    // 下载PDF文件
    const downloadPdf = async (pdf) => {
      if (!pdf.downloading) {
        pdf.downloading = true;
        try {
          const response = await request({
            url: ip + `/api/file/download/${pdf.fileId}`,
            method: 'GET',
            responseType: 'blob'
          });
          
          // 创建下载链接
          const blob = new Blob([response.data], { type: 'application/pdf' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = pdf.articleTitle || `文件_${pdf.fileId}.pdf`;
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          
          // 清理
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          ElMessage.success('下载成功');
        } catch (error) {
          console.error('下载失败:', error);
          ElMessage.error('下载失败，请重试');
        } finally {
          pdf.downloading = false;
        }
      }
    };

    // 处理视图切换
    const handleViewChange = async (view) => {
      try {
        currentView.value = view;
        if (view === 'file') {
          currentPdf.value = null;
          qaList.value = [];
          fileStatusList.value = [];
          fileViewType.value = 'pending'; // 自动设置为未处理状态
          await fetchFileViewList();
        } else if (view === 'last') {
          currentPdf.value = null;
          qaList.value = [];
          fileStatusList.value = [];
          qaViewType.value = 'pending'; // 自动设置为未处理状态
          await fetchPdfList();
          await fetchStats();
          // 如果有文件，自动选择第一个文件
          if (pdfList.value.length > 0) {
            await selectPdf(pdfList.value[0]);
          }
        }
      } catch (error) {
        console.error('切换视图失败:', error);
        ElMessage.error('切换视图失败');
      }
    };

    // 获取文件列表视图数据
    const fetchFileViewList = async () => {
      try {
        loading.value = true;
        //  const response = await request.get('http://10.137.10.169:8080/api/me/reviewTask/file');
        const response = await request.get(ip + `/api/me/reviewTask/file`);
        console.log("文件列表数据：", response.data);
        
        if (response.data.code === 200) {
          // 获取每个文件的详细信息
          const fileDetails = await Promise.all(
            response.data['file-view'].map(async (item) => {
              try {
                // const detailResponse = await request.get(`http://10.137.10.169:8080/api/file/info/${item.fileId}`);
                const detailResponse = await request.get(ip + `/api/file/info/${item.fileId}`);
                console.log("第1052行");
                if (detailResponse.data.code === 200) {
                  return {
                    ...item,
                    downloading: false,
                    status: 0,
                    fileName: detailResponse.data.data.fileName
                  };
                }
                return {
                  ...item,
                  downloading: false,
                  status: 0,
                  fileName: `文件${item.fileId}`
                };
              } catch (error) {
                console.error(`获取文件${item.fileId}详情失败:`, error);
                return {
                  ...item,
                  downloading: false,
                  status: 0,
                  fileName: `文件${item.fileId}`
                };
              }
            })
          );
          
          fileViewList.value = fileDetails;
        } else {
          throw new Error(response.data.msg || '获取文件列表失败');
        }
      } catch (error) {
        console.error('获取文件列表失败:', error);
        ElMessage.error('获取文件列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 通过文件
    const approveFile = async (file) => {
      try {
        const existingIndex = fileStatusList.value.findIndex(item => item.id === file.id);
        if (existingIndex !== -1) {
          fileStatusList.value[existingIndex].status = 1;
        } else {
          fileStatusList.value.push({
            id: file.id,
            status: 1
          });
        }
        file.status = 1;
        ElMessage.success('已标记为通过');
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    };

    // 驳回文件
    const rejectFile = async (file) => {
      try {
        const existingIndex = fileStatusList.value.findIndex(item => item.id === file.id);
        if (existingIndex !== -1) {
          fileStatusList.value[existingIndex].status = 2;
        } else {
          fileStatusList.value.push({
            id: file.id,
            status: 2
          });
        }
        file.status = 2;
        ElMessage.success('已标记为驳回');
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    };

    // 提交文件状态
    const submitFileStatus = async (file) => {
      try {
        loading.value = true;
        const fileStatus = fileStatusList.value.find(item => item.id === file.id);
        if (!fileStatus) {
          ElMessage.warning('请先选择通过或驳回');
          return;
        }

        // const response = await request.post('http://10.137.10.169:8080/api/view/file', [fileStatus]);
        const response = await request.post(ip + `/api/view/file`, [fileStatus]);
        
        if (response.data.code === 200) {
          ElMessage.success('提交成功');
          // 从状态列表中移除已提交的文件
          fileStatusList.value = fileStatusList.value.filter(item => item.id !== file.id);
          // 刷新文件列表
          await fetchFileViewList();
          // 更新右侧预览信息
          if (previewItem.value && previewItem.value.id === file.id) {
            const updatedItem = fileViewList.value.find(item => item.id === file.id);
            if (updatedItem) {
              previewItem.value = JSON.parse(JSON.stringify(updatedItem));
            } else {
              previewItem.value = null;
            }
          }
        } else {
          throw new Error(response.data.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      } finally {
        loading.value = false;
      }
    };

    // 刷新文件列表
    const refreshFileList = async () => {
      await fetchFileViewList();
    };

    // 获取统计数据
    const fetchStats = async () => {
      try {
        // const response = await request.get('http://10.137.10.169:8080/api/Static/handle');
        const response = await request.get(ip + `/api/Static/handle`);
        if (response.data && response.data.code === 200) {
          stats.value = {
            pending: response.data.data.count_file || 0,
            processed: response.data.data.counted_file || 0,
            qaPending: response.data.data.qaCount || 0,
            qaProcessed: response.data.data.qaCounted || 0
          };
        }
        // console.log("统计数据：", stats.value);
      } catch (error) {
        console.error('获取统计数据失败:', error);
        ElMessage.error('获取统计数据失败');
      }
    };

    // 过滤文件列表
    const filteredFileList = computed(() => {
      return fileViewList.value;
    });

    // 分页文件列表
    const paginatedFileList = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredFileList.value.slice(start, end);
    });

    // 处理文件预览
    const previewDetail = (item) => {
      previewItem.value = JSON.parse(JSON.stringify(item));
    };

    // 处理文件大小变化
    const handleSizeChange = (val) => {
      // 不再需要此函数
    };

    // 处理文件当前页变化
    const handleCurrentChange = (val) => {
      currentPage.value = val;
    };

    // 获取文件状态文本
    const getFileStatusText = (status) => {
      const statusMap = {
        '-2': 'AI分析中',
        '-1': 'AI分析失败',
        '0': 'AI分析完成',
        '1': '专家审核失败',
        '2': '专家审核成功',
        '3': '专家审核成功',
        '5': '专家审核成功',
        '7': '全部通过',
        '8': 'AI分析失败',
        '9': 'AI分析中'
      };
      return statusMap[status] || '未知状态';
    };

    // 获取文件状态标签类型
    const getFileStatusType = (status) => {
      const typeMap = {
        '-2': 'primary',
        '-1': 'danger',
        '0': 'success',
        '1': 'danger',
        '2': 'success',
        '3': 'success',
        '5': 'success',
        '7': 'success',
        '8': 'danger',
        '9': 'info'
      };
      return typeMap[status] || 'info';
    };

    // 计算当前页的PDF列表
    const paginatedPdfList = computed(() => {
      const start = (pdfCurrentPage.value - 1) * pdfPageSize.value;
      const end = start + pdfPageSize.value;
      return pdfList.value.slice(start, end);
    });

    // 处理PDF列表分页大小变化
    const handlePdfSizeChange = (val) => {
      // 不再需要此函数
    };

    // 处理PDF列表页码变化
    const handlePdfCurrentChange = (val) => {
      pdfCurrentPage.value = val;
    };

    // 处理QA视图类型切换
    const handleQaViewTypeChange = async (type) => {
      try {
        loading.value = true;
        if (type === 'processed') {
          // 获取已处理文件列表
          // const response = await request.get('http://10.137.10.169:8080/api/Static/handle');
          const response = await request.get(ip + `/api/Static/handle`);
          if (response.data.code === 200) {
            const processedTaskIds = response.data.data.processedTasks || [];
            console.log("已处理文件列表：", response.data.data.processedTasks);
            
            // 获取每个文件的详细信息
            const fileDetails = await Promise.all(
              processedTaskIds.map(async (fileId) => {
                try {
                  // const detailResponse = await request.get(`http://10.137.10.169:8080/api/file/info/conf/${fileId}`);
                  const detailResponse = await request.get(ip + `/api/file/info/conf/${fileId}`);
                  console.log("第1291行");
                  if (detailResponse.data.code === 200) {
                    const fileData = detailResponse.data.data;
                    return {
                      id: fileData.id,
                      fileId: fileData.fileId,
                      articleTitle: fileData.articleTitle,
                      major: fileData.major,
                      status: fileData.status,
                      createTime: fileData.createTime,
                      updateTime: fileData.updateTime,
                      downloading: false,
                      fileName: fileData.articleTitle || `文件${fileId}`
                    };
                  }
                  return null;
                } catch (error) {
                  console.error(`获取文件${fileId}详情失败:`, error);
                  return null;
                }
              })
            );
            
            // 过滤掉获取失败的文件
            pdfList.value = fileDetails.filter(file => file !== null);
            
            // 如果当前有预览项，更新预览项的详细信息
            if (currentPdf.value) {
              const updatedItem = fileDetails.find(item => item.id === currentPdf.value.id);
              if (updatedItem) {
                currentPdf.value = JSON.parse(JSON.stringify(updatedItem));
              } else {
                currentPdf.value = null;
              }
            }
          }
        } else {
          // 切换回未处理视图时，重新获取未处理列表
          await fetchPdfList();
          // 如果当前有预览项，更新预览项的详细信息
          if (currentPdf.value) {
            const updatedItem = pdfList.value.find(item => item.id === currentPdf.value.id);
            if (updatedItem) {
              currentPdf.value = JSON.parse(JSON.stringify(updatedItem));
            } else {
              currentPdf.value = null;
            }
          }
        }
      } catch (error) {
        console.error('获取文件列表失败:', error);
        ElMessage.error('获取文件列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-';
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '-';
        return date.toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false 
        });
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '-';
      }
    };

    // 处理文件视图类型切换
    const handleFileViewTypeChange = async (type) => {
      try {
        loading.value = true;
        if (type === 'processed') {
          // const response = await request.get('http://10.137.10.169:8080/api/me/submitted');
          const response = await request.get(ip + `/api/me/submitted`);
          if (response.data.code === 200) {
            // 获取每个文件的详细信息
            const fileDetails = await Promise.all(
              response.data['file-view'].map(async (item) => {
                try {
                  // const detailResponse = await request.get(`http://10.137.10.169:8080/api/file/info/${item.fileId}`);
                  const detailResponse = await request.get(ip + `/api/file/info/${item.fileId}`);
                  console.log("第1383行");
                  if (detailResponse.data.code === 200) {
                    return {
                      ...item,
                      downloading: false,
                      fileName: detailResponse.data.data.fileName
                    };
                  }
                  return {
                    ...item,
                    downloading: false,
                    fileName: `文件${item.fileId}`
                  };
                } catch (error) {
                  console.error(`获取文件${item.fileId}详情失败:`, error);
                  return {
                    ...item,
                    downloading: false,
                    fileName: `文件${item.fileId}`
                  };
                }
              })
            );
            fileViewList.value = fileDetails;
            // 如果当前有预览项，更新预览项的详细信息
            if (previewItem.value) {
              const updatedItem = fileDetails.find(item => item.id === previewItem.value.id);
              if (updatedItem) {
                previewItem.value = JSON.parse(JSON.stringify(updatedItem));
              } else {
                previewItem.value = null;
              }
            }
          }
        } else {
          // 切换回未处理视图时，重新获取未处理列表
          await fetchFileViewList();
          // 如果当前有预览项，更新预览项的详细信息
          if (previewItem.value) {
            const updatedItem = fileViewList.value.find(item => item.id === previewItem.value.id);
            if (updatedItem) {
              previewItem.value = JSON.parse(JSON.stringify(updatedItem));
            } else {
              previewItem.value = null;
            }
          }
        }
      } catch (error) {
        console.error('获取文件列表失败:', error);
        ElMessage.error('获取文件列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取QA对状态文本
    const getQaStatusText = (status) => {
      switch (status) {
        case 1:
          return '等待审核';
        case 2:
          return '计算机老师审核通过';
        case 3:
          return '计算机老师审核不通过';
        case 4:
          return '最后审核通过';
        case 5:
          return '最后审核不通过';
        case 6:
          return '被标记';
        default:
          return '未知状态';
      }
    };

    // 获取QA对状态类型（用于标签颜色）
    const getQaStatusType = (status) => {
      switch (status) {
        case 1:
          return 'info';     // 等待审核 - 灰色
        case 2:
          return 'success';  // 计算机老师审核通过 - 绿色
        case 3:
          return 'danger';   // 计算机老师审核不通过 - 红色
        case 4:
          return 'success';  // 最后审核通过 - 绿色
        case 5:
          return 'danger';   // 最后审核不通过 - 红色
        case 6:
          return 'warning';  // 被标记 - 黄色
        default:
          return 'info';     // 默认 - 灰色
      }
    };

    // 下载QA对为Json文件
    const downloadQaJson = () => {
      if (!qaList.value || qaList.value.length === 0) {
        ElMessage.warning('暂无QA对可下载');
        return;
      }
      const data = qaList.value.map(qa => ({
        instruction: qa.instruction,
        output: (qa.statusCode === 3 ? qa.llmOutput : qa.output),
        input: '',
        system: ''
      }));
      const jsonStr = JSON.stringify(data, null, 2);
      const blob = new Blob([jsonStr], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = (currentPdf.value?.articleTitle || 'QA对') + '.json';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      ElMessage.success('QA对Json文件下载已开始');
    };

    // 处理修改密码
    const handleChangePassword = () => {
      router.push({
        path: '/update-pass',
        query: {
          username: username.value
        }
      });
    };

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await axios({
          method: 'get',
          url: ip + '/api/me',
          headers: {
            'auth': localStorage.getItem('auth')
          }
        });
        
        if (response.data && response.data.code === 200) {
          realName.value = response.data.data.realName || '用户';
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    onMounted(() => {
      username.value = localStorage.getItem('username') || '用户';
      // 获取用户信息
      fetchUserInfo();
      // 根据当前视图类型调用相应的方法
      if (currentView.value === 'file') {
        fetchFileViewList();
      } else {
        fetchPdfList();
      }
      // 获取统计数据
      fetchStats();
      // 设置定时器，每30秒刷新一次统计数据
      const timer = setInterval(() => {
        fetchStats();
      }, 30000);

      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(timer);
      });
    });

    return {
      username,
      realName, // 添加realName到返回值
      pdfList,
      fileViewList,
      currentView,
      currentPdf,
      qaList,
      hasChanges,
      loading,
      selectPdf,
      editQa,
      confirmEdit,
      cancelEdit,
      saveAllChanges,
      handleLogout,
      currentPage,
      currentQa,
      approveQa,
      rejectQa,
      downloadPdf,
      cancelApprove,
      cancelReject,
      getStatusText,
      getStatusType,
      handleViewChange,
      approveFile,
      rejectFile,
      refreshFileList,
      submitFileStatus,
      stats,
      pageSize,
      previewItem,
      filteredFileList,
      paginatedFileList,
      previewDetail,
      handleCurrentChange,
      getFileStatusText,
      getFileStatusType,
      pdfCurrentPage,
      pdfPageSize,
      paginatedPdfList,
      handlePdfCurrentChange,
      qaViewType,
      handleQaViewTypeChange,
      formatDate,
      fileViewType,
      handleFileViewTypeChange,
      getQaStatusText,
      getQaStatusType,
      downloadQaJson,
      handleChangePassword,
      expandedBlocks,
      toggleBlock,
    };
  }
};
</script>

<style scoped>
.a4-container {
  width: 100%;
  min-width: 1200px;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.header h1 {
  color: #2c3e50;
  font-size: 24px;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome {
  font-size: 16px;
  color: #606266;
}

.username {
  font-size: 16px;
  color: #409EFF;
  margin: 0 10px;
  font-weight: 600;
}

.logout-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
}

.logout-btn:hover {
  background-color: #e64242;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

.stats-cards {
  margin: 20px 0;
}

.processed-count-text {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  color: #606266;
  margin: 20px 0;
  padding: 12px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.processed-count-text .el-icon {
  color: #409EFF;
}

.processed-count-text .el-divider {
  margin: 0 12px;
  height: 1em;
}

.view-switch {
  margin: 0 0 20px 0;
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.view-switch :deep(.el-radio-group) {
  display: inline-flex;
  gap: 10px;
}

.view-switch :deep(.el-radio-button__inner) {
  padding: 12px 30px;
  font-size: 14px;
  font-weight: 500;
}

.main-content {
  display: flex;
  gap: 20px;
  min-height: 0;
  height: calc(100vh - 180px);
  margin-top: 20px;
  padding: 0 20px;
  overflow: hidden;
}

.file-list-section, .detail-preview {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin-bottom: 20px;
}

.file-list-section {
  flex: 3;
  max-width: 60%;
  min-width: 350px;
  height: 100%;
  overflow: hidden;
}

.detail-preview {
  flex: 1;
  max-width: 40%;
  min-width: 500px;
  height: fit-content;
  max-height: none;
  overflow-y: visible;
  flex-shrink: 0;
  padding-right: 10px;
  box-sizing: border-box;
}

.file-list-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
}

.search-box {
  margin-bottom: 20px;
  padding: 0 20px;
  flex-shrink: 0;
}

.file-list {
  max-height: 400px;
  min-height: 120px;
  overflow-y: auto;
  padding: 0 10px;
  margin-bottom: 10px;
  background: #fff;
  border-radius: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #ebeef5;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.file-item:hover {
  background-color: #ecf5ff;
}

.file-item-active {
  background-color: #e6f2ff !important;
  border-left: 4px solid #409EFF;
  padding-left: 11px;
}

.file-icon {
  width: 40px;
  height: 40px;
  margin-right: 15px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.file-icon .el-icon {
  font-size: 24px;
  color: #909399;
}

.file-info {
  flex: 1;
  margin-right: 15px;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
}

.file-time {
  font-size: 12px;
  color: #909399;
}

.file-actions {
  display: flex;
  gap: 8px;
  margin-right: 15px;
}

.file-status {
  position: absolute;
  top: 8px;
  right: 12px;
  font-size: 12px;
  padding: 0 8px;
  height: 20px;
  line-height: 20px;
}

.preview-header {
  padding: 12px 0;
}

.preview-header h3 {
  margin: 0;
  font-size: 16px;
}

.preview-content {
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  overflow: visible;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  width: 100%;
  box-sizing: border-box;
  flex-wrap: wrap;
}

.preview-actions .el-button {
  margin: 5px;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 0 0 0;
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 统计面板样式 */
.stats-panel {
  display: flex;
  gap: 15px;
  margin: 10px 0;
  justify-content: center;
}

.stats-card {
  background-color: white;
  border-radius: 6px;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  min-width: 140px;
  box-shadow: 0 2px 6px 0 rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 8px 0 rgba(0,0,0,0.15);
}

.stats-icon {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}

.stats-icon.pending {
  background-color: #e6a23c20;
  color: #e6a23c;
}

.stats-icon.processed {
  background-color: #67c23a20;
  color: #67c23a;
}

.stats-icon .el-icon {
  font-size: 14px;
}

.stats-content {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-value {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 13px;
  color: #909399;
  line-height: 1;
}

/* 调整描述列表样式 */
:deep(.el-descriptions) {
  width: 100%;
  margin-bottom: 20px;
}

:deep(.el-descriptions__body) {
  background-color: #fff;
  width: 100%;
  overflow: visible;
}

:deep(.el-descriptions__table) {
  width: 100%;
  table-layout: fixed;
}

:deep(.el-descriptions__cell) {
  padding: 12px 15px;
  width: 100%;
  vertical-align: top;
}

:deep(.el-descriptions__label) {
  width: 80px !important;
  min-width: 80px !important;
  max-width: 80px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-descriptions__content) {
  max-width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 确保内容块正确显示 */
.content-block {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin: 5px 0;
  width: 450px;
  box-sizing: border-box;
  font-size: 14px;
  max-height: 100px;
  overflow: hidden;
  position: relative;
  transition: max-height 0.3s ease;
}

.content-block.expanded {
  max-height: none;
}

.content-block::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 32px;
  background: linear-gradient(180deg, transparent, #f8f9fa);
  pointer-events: none;
  opacity: 1;
  transition: opacity 0.3s ease;
}

.content-block.expanded::after {
  opacity: 0;
}

.expand-btn {
  display: block;
  text-align: left;
  color: #409EFF;
  cursor: pointer;
  padding: 4px 12px;
  font-size: 13px;
  margin-top: 4px;
  user-select: none;
}

.expand-btn:hover {
  color: #66b1ff;
}

/* 调整预览卡片样式 */
.detail-preview :deep(.el-card) {
  width: 100%;
  margin-bottom: 20px;
  height: auto;
}

.detail-preview :deep(.el-card__body) {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  height: auto;
}

/* 文本省略组件样式 */
.text-ellipsis-container {
  position: relative;
  width: 100%;
}

.text-collapsed {
  position: relative;
  overflow: hidden;
  max-height: none !important;
}

.text-collapsed::after {
  display: none;
}

.toggle-expand {
  display: none;
}

/* QA对样式 */
.qa-item {
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 24px;
  transition: all 0.3s;
  background-color: #fff;
  width: 100%;
  margin-bottom: 20px;
}

.qa-item-current {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.qa-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.qa-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.qa-index {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: bold;
  color: #409EFF;
}

.qa-status {
  display: flex;
  align-items: center;
  gap: 5px;
}

.qa-content {
  margin-top: 20px;
}

.qa-field {
  margin-bottom: 24px;
}

.qa-field label {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #606266;
  font-weight: bold;
  font-size: 15px;
}

.qa-text {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
  min-height: 24px;
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.6;
}

.qa-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
}

.qa-edit-actions,
.qa-review-actions {
  display: flex;
  gap: 12px;
}

.qa-feedback {
  margin-top: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.feedback-text {
  color: #F56C6C;
  font-size: 14px;
  line-height: 1.6;
  margin-top: 8px;
}

/* 调整输入框样式 */
.qa-field .el-textarea__inner {
  font-size: 14px;
  line-height: 1.6;
  padding: 12px;
}

/* 调整按钮样式 */
.qa-actions .el-button {
  padding: 10px 20px;
  font-size: 14px;
}

/* 调整标签样式 */
.qa-status .el-tag {
  padding: 6px 12px;
  font-size: 13px;
}

.submit-section {
  margin-top: 30px;
  padding: 20px;
  display: flex;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
}

.submit-section .el-button {
  padding: 12px 30px;
  font-size: 16px;
}

.submit-section .el-button .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

/* 自定义滚动条样式 */
.file-list::-webkit-scrollbar {
  width: 8px;
}

.file-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.file-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

.file-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.ai-output {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  color: #67c23a;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-actions .el-radio-group {
  margin-right: 10px;
}

.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 历史列表部分样式 */
.history-list-section {
  margin-top: 20px;
  display: flex;
  gap: 20px;
  min-width: 1200px;
}

.history-list-card {
  flex: 1;
  max-width: 50%;
  min-width: 500px;
  margin-bottom: 30px;
  flex-shrink: 0;
  overflow-x: hidden;
}

.detail-preview {
  flex: 1;
  max-width: 50%;
  min-width: 500px;
  height: fit-content;
  max-height: none;
  overflow-y: visible;
  flex-shrink: 0;
  padding-right: 10px;
  box-sizing: border-box;
}

.file-list {
  padding: 0 10px;
  height: calc(8 * 60px);
  overflow-y: auto;
  overflow-x: hidden;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fff;
  width: 100%;
  box-sizing: border-box;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
  gap: 10px;
  height: 60px;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden;
}

.file-item:hover {
  background-color: #ecf5ff;
}

.file-item-active {
  background-color: #e6f2ff !important;
  border-left: 4px solid #409EFF;
  padding-left: 11px;
}

.file-icon {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ecf5ff 0%, #e6f2ff 100%);
  border-radius: 8px;
  margin-right: 12px;
  transition: all 0.3s ease;
}

.file-icon .el-icon {
  font-size: 24px;
  color: #409EFF;
  transition: all 0.3s ease;
}

.file-item:hover .file-icon {
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  transform: scale(1.05);
}

.file-item:hover .file-icon .el-icon {
  color: #ffffff;
}

.file-item-active .file-icon {
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
}

.file-item-active .file-icon .el-icon {
  color: #ffffff;
}

.file-info {
  flex: 1;
  min-width: 0;
  margin-right: 15px;
}

.file-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
}

.file-time {
  font-size: 12px;
  color: #909399;
}

.file-actions {
  display: flex;
  gap: 8px;
  margin-right: 15px;
  flex-shrink: 0;
  flex-wrap: nowrap;
  opacity: 0;
  transition: all 0.3s ease;
  transform: translateX(10px);
}

.file-item:hover .file-actions {
  opacity: 1;
  transform: translateX(0);
}

.file-status {
  position: static;
  flex-shrink: 0;
  min-width: 90px;
  max-width: 120px;
  text-align: center;
  font-size: 13px;
  white-space: nowrap;
  opacity: 1;
  transform: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header .header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-actions .el-radio-group {
  margin-right: 10px;
}

/* 响应式支持 */
@media (max-width: 1200px) {
  .history-list-section {
    flex-direction: row;
    overflow-x: auto;
  }
  
  .history-list-card,
  .detail-preview {
    min-width: 500px;
    max-width: 50%;
  }
}

/* 预览内容样式 */
.preview-content {
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  overflow: visible;
}

.preview-content .el-descriptions {
  margin-bottom: 20px;
}

.preview-content .el-descriptions__content {
  padding: 12px 15px;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  padding: 10px 0 0 0;
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* QA对样式 */
.qa-item {
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 24px;
  transition: all 0.3s;
  background-color: #fff;
  width: 100%;
  margin-bottom: 20px;
}

.qa-item-current {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.qa-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.qa-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.qa-index {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: bold;
  color: #409EFF;
}

.qa-status {
  display: flex;
  align-items: center;
  gap: 5px;
}

.qa-content {
  margin-top: 20px;
}

.qa-field {
  margin-bottom: 24px;
}

.qa-field label {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #606266;
  font-weight: bold;
  font-size: 15px;
}

.qa-text {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
  min-height: 24px;
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.6;
}

.qa-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
}

.qa-edit-actions,
.qa-review-actions {
  display: flex;
  gap: 12px;
}

.qa-feedback {
  margin-top: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.feedback-text {
  color: #F56C6C;
  font-size: 14px;
  line-height: 1.6;
  margin-top: 8px;
}

.ai-output {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  color: #67c23a;
}

.submit-section {
  margin-top: 30px;
  padding: 20px;
  display: flex;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
}

.submit-section .el-button {
  padding: 12px 30px;
  font-size: 16px;
}

.submit-section .el-button .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  margin: 0 10px;
}

.user-profile:hover {
  background-color: #ecf5ff;
}

.user-icon {
  font-size: 18px;
  color: #409EFF;
  transition: all 0.3s ease;
}

.user-profile:hover .user-icon {
  transform: scale(1.1);
}

.username {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  transition: all 0.3s ease;
}

.user-profile:hover .username {
  color: #66b1ff;
}

.real-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 4px;
}

.username {
  font-size: 16px;
  color: #409EFF;
  margin: 0 10px;
  font-weight: 600;
}
</style> 
